##
# This class handles exams taken by students for teachers
class StudentExamController < ApplicationController
	helper :paginator
	helper :right
  helper :gradebook
	include PaginatorHelper
	include RightHelper
  include GradebookHelper
  
  layout 'scaffold'
  
	# Session must be active
	verify :session => 'user',
				 :redirect_to => { :controller => 'user', :action => :login },
				 :add_flash => { :error => 
								         'you must be logged in to view student-made-exams' 
                       }
                       
  # only teachers may access this controller
	before_filter :verify_teacher
  # only the owner of a result can destroy and show it
  before_filter :verify_owner, :only => [ :destroy, :show ]
  
  ##
  # this method redirects to the list method
  def index
    list
    render :action => 'list'
  end
  
  ##
  # this method displays all the taken exams
  def list
    @exams = Exam.find(:all, :conditions => { :user_id => session['user'].id },
                             :order => 'id desc')
    @exam_pages, @exams = paginate_collection @exams, :per_page => 10,
                                                      :page => params[:page]
  end
  
  ##
  # this method destroys an exam-result
  def destroy
    result = ExamResult.find(params[:id])
    # first of all delete user_answers...
    # we are using here plain sql, because it should be more readable...
    sql = ActiveRecord::Base.connection
    sql.begin_db_transaction
    sql.delete("delete from user_answers " \
               "where user_id = '#{ result.user_id }' " \
               "and time = '#{ result.time.to_s(:db) }' " \
               "and answer_id in ( " \
                  "select answers.id as id "\
                  "from answers, questions, exams " \
                  "where answers.question_id = questions.id " \
                  "and questions.exam_id = exams.id " \
                  "and exams.id = #{ result.exam_id }) ")
    sql.commit_db_transaction
    result.destroy
    redirect_to :action => 'list'
  end
  
  ##
  # this method shows an exam-result
  def show
    @result = ExamResult.find(params[:id])
    @exam = @result.exam
    @user_answers = find_user_answers(@exam, @result.user)
  end
  
  private
  
  ##
  # this method verifies that the exam-result int the GET-variable is owned
  # by the currently logged in user
  def verify_owner
    result = ExamResult.find(params[:id])
    if result.exam.user != session['user']
      flash[:error] = "Error, this Exam doesn't belongs to you"
      redirect_to :action => 'list'
    end
  end
end
